package com.forevershine.common.util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.opensymphony.xwork2.ActionContext;

public class HttpRequestResponseHelper {

	private final static int BUFF_SIZE = 4096;

	public static void writeJsonResponse(String msg) {
		ActionContext context = ActionContext.getContext();
		HttpServletResponse response = null;
		PrintWriter pw = null;
		try {
			response = ((HttpServletResponse) context
					.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE));
			response.setContentType("application/json;charset=UTF-8");
			pw = ((HttpServletResponse) context
					.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE))
					.getWriter();
			pw.write(msg);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pw.close();
		}
	}

	public static void downloadFile(String path) {
		ActionContext context = ActionContext.getContext();
		HttpServletResponse response = null;
		File file = new File(path);
		response = ((HttpServletResponse) context
				.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE));
		ServletOutputStream op = null;
		DataInputStream in = null;
		try {
			op = response.getOutputStream();
			in = new DataInputStream(new FileInputStream(file));
			response.setContentType("application/octet-stream");
			response.setContentLength((int) file.length());
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ file.getName() + "\"");

			byte[] bbuf = new byte[BUFF_SIZE];

			int length = -1;
			while ((in != null) && ((length = in.read(bbuf)) != -1)) {
				op.write(bbuf, 0, length);
			}

			in.close();
			op.flush();
			op.close();
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					in = null;
				}
			}
			if (op != null) {
				try {
					op.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					op = null;
				}
			}
		}
	}

	public static String getParam(String key) {
		Object value = ActionContext.getContext().getParameters().get(key);
		if (value != null) {
			if (value instanceof Object[]) {
				return ((Object[]) value)[0].toString();
			} else {
				return value.toString();
			}
		} else {
			return null;
		}
	}

	public static String getSessionValue(String key) {
		Object value = ActionContext.getContext().getSession().get(key);
		if (value != null) {
			if (value instanceof Object[]) {
				return ((Object[]) value)[0].toString();
			} else {
				return value.toString();
			}
		} else {
			return null;
		}
	}

}
